package com.yao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yao.common.Result;
import com.yao.dto.OrderDto;
import com.yao.dto.OrderListDto;
import com.yao.dto.ShoppingDto;
import com.yao.po.*;
import com.yao.service.IFlowersService;
import com.yao.service.IOrderService;
import com.yao.service.IOrderpayService;
import com.yao.service.IShoppingCartService;
import com.yao.utils.BeanUtils;
import com.yao.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {

    private final IOrderpayService orderpayService;
    private final IOrderService orderService;
    private final IFlowersService flowersService;
    private final IShoppingCartService shoppingCartService;
    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    public OrderController(IOrderpayService orderpayService, IOrderService orderService, IFlowersService flowersService, IShoppingCartService shoppingCartService) {
        this.orderpayService = orderpayService;
        this.orderService = orderService;
        this.flowersService = flowersService;
        this.shoppingCartService = shoppingCartService;
    }

    /**
     * 获取订单详细信息
     *
     * @return 订单信息
     */
    @GetMapping("/trade")
    public Result<Object> getOrder() {
        log.info("获取订单信息...");
        List<ShoppingCart> list = shoppingCartService
                .lambdaQuery()
                .eq(ShoppingCart::getOpenId, UserContext.getUser())
                .eq(ShoppingCart::getIsChecked, 1)
                .list();
        ShoppingDto dto = new ShoppingDto();
        dto.setCartVoList(list);
        dto.setTotalCount(list.size());
        BigDecimal totalAmount = BigDecimal.ZERO;
        // 初始化totalAmount
        // 计算总金额
        for (ShoppingCart shoppingCart : list) {
            if (shoppingCart.getPrice() != null) {
                totalAmount = totalAmount.add(shoppingCart.getPrice()
                        .multiply(BigDecimal.valueOf(shoppingCart.getCount()))
                );
            }
        }
        dto.setTotalAmount(totalAmount); // 最后设置到dto中
        return Result.success(dto);
    }

    @GetMapping("/buy/{goodsId}")
    public Result<Object> buyOrder(@PathVariable("goodsId") Long goodsId, @RequestParam("blessing") String blessing) {
        log.info("购买商品...");
        Flowers byId = flowersService.getById(goodsId);
        ShoppingDto dto = new ShoppingDto();
        ShoppingCart shoppingCart = BeanUtils.copyBean(byId, ShoppingCart.class);
        shoppingCart.setGoodsId(byId.getId());
        shoppingCart.setCount(1);
        shoppingCart.setOpenId(UserContext.getUser());
        shoppingCart.setBlessing(blessing);
        shoppingCart.setIsChecked(1);
        dto.setTotalAmount(shoppingCart.getPrice());
        dto.setTotalCount(1);
        dto.setCartVoList(List.of(shoppingCart));
        return Result.success(dto);
    }

    //orderList.orderNo
    //item.orderStatus

    @PostMapping("/submitOrder")
    @Transactional
    public Result<Object> submitOrder(@RequestBody Order order) {
        log.info("提交订单...");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        // 保存订单信息
        // 保存购物车信息
        // 清空购物车
        order.setOpenId(UserContext.getUser());
        order.setOrderNo(uuid);
        orderService.save(order);

        List<ShoppingCart> cartList = order.getCartList();
        List<Orderpay> iOrderpayServices = new ArrayList<>();
        for (ShoppingCart cart : cartList) {
            Orderpay orderpay = BeanUtils.copyBean(cart, Orderpay.class);
            orderpay.setOrderNo(uuid);
            orderpay.setOrderStatus(1);
            iOrderpayServices.add(orderpay);
        }

        //删除购买了的商品
        shoppingCartService.remove(Wrappers.<ShoppingCart>lambdaQuery()
                .eq(ShoppingCart::getOpenId, UserContext.getUser())
                .eq(ShoppingCart::getIsChecked, 1));

        orderpayService.saveBatch(iOrderpayServices);
        return Result.success(uuid);
    }

    @GetMapping("/queryPayStatus/{orderNo}")
    public Result<Object> getOrderStatus(@PathVariable("orderNo") String orderNo) {
        log.info("获取订单状态...");
        Order one = orderService
                .lambdaQuery()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getOpenId, UserContext.getUser())
                .one();
        if (one != null) {
            if (one.getOrderStatus() == 0) {
                return Result.success("订单尚未支付");
            }
            return Result.success("订单已支付");
        } else {
            return Result.error("订单不存在");
        }
    }

    @GetMapping("/order/{page}/{limit}")
    public Result<Object> getOrderList(@PathVariable("page") Integer page, @PathVariable("limit") Integer limit) {
        log.info("获取订单列表...");
        OrderDto orderDto = new OrderDto();
        List<OrderListDto> orderListDto1 = new ArrayList<>();

        IPage<Orderpay> flowersPage = new Page<>(page, limit);
        LambdaQueryWrapper<Orderpay> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orderpay::getOpenId, UserContext.getUser())
                .orderBy(true, true, Orderpay::getUpdateTime, Orderpay::getCreateTime);

        try {
            IPage<Orderpay> page1 = orderpayService.page(flowersPage, wrapper);

            List<Orderpay> records = page1.getRecords();
            Map<String, List<Orderpay>> collect = records.stream().collect(Collectors.groupingBy(Orderpay::getOrderNo));

            collect.forEach(
                    (key, value) -> {
                        orderDto.setTotal(value.size()+orderDto.getTotal());
                        OrderListDto orderListDto = new OrderListDto();
                        orderListDto.setOrderDetailList(value);
                        orderListDto.setOrderNo(key);
                        orderListDto.setOrderStatus(value.get(0).getOrderStatus());
                        orderListDto.setTotalAmount(value.stream()
                                .map(cart -> cart.getPrice().multiply(BigDecimal.valueOf(cart.getCount())))
                                .reduce(BigDecimal.ZERO, BigDecimal::add));
                        orderListDto1.add(orderListDto);
                    }
            );

            orderDto.setRecords(orderListDto1);
        } catch (Exception e) {
            return Result.success(null);
        }
        return Result.success(orderDto);
    }
}
